import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:fsharing/core/models/cart_list.dart';
import 'package:fsharing/core/models/product_detail.dart';
import 'package:fsharing/core/viewmodels/pages/cart/cart_change_model.dart';
import 'package:fsharing/core/viewmodels/pages/cart/cart_list_model.dart';
import 'package:fsharing/core/viewmodels/pages/cart/cart_remove_model.dart';
import 'package:fsharing/core/viewmodels/pages/mine/order/order_check_model.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';
import 'package:fsharing/main.dart';
import 'package:fsharing/ui/widgets/background_container.dart';
import 'package:fsharing/ui/widgets/check_box.dart';
import 'package:fsharing/ui/widgets/quantitiy_counter.dart';
import 'package:fsharing/ui/widgets/round_back_button.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';

/// 购物车
class CartPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (context) => CartListModel(Provider.of(context, listen: false)),
        ),
        ChangeNotifierProvider(
          create: (context) => CartChangeModel(Provider.of(context, listen: false)),
        ),
        ChangeNotifierProvider(
          create: (context) => CartRemoveModel(Provider.of(context, listen: false)),
        ),
        ChangeNotifierProvider(
          create: (context) => OrderCheckModel(Provider.of(context, listen: false)),
        ),
      ],
      child: BackgroundContainer(
        child: Consumer<CartListModel>(
          builder: (context, model, child) {
            switch (model.viewState) {
              case ViewState.busy:
                return Scaffold(
                  appBar: child,
                  body: Center(
                    child: CircularProgressIndicator(),
                  ),
                );
              case ViewState.error:
                return Scaffold(
                  appBar: child,
                  body: Center(
                    child: Text(model.errorMessage),
                  ),
                );
              case ViewState.success:
                return Scaffold(
                  appBar: child,
                  body: _BodyWidget(
                    list: model.cartList.carts,
                  ),
                  bottomNavigationBar: _BottomWidget(
                    cartList: model.cartList,
                  ),
                );
              default:
                return Container();
            }
          },
          child: AppBar(
            leading: RoundBackButton(),
            title: Text('购物车'),
          ),
        ),
      ),
    );
  }
}

/// Tab Item Page
class CartTabItemPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (context) => CartListModel(Provider.of(context, listen: false)),
        ),
        ChangeNotifierProvider(
          create: (context) => CartChangeModel(Provider.of(context, listen: false)),
        ),
        ChangeNotifierProvider(
          create: (context) => CartRemoveModel(Provider.of(context, listen: false)),
        ),
        ChangeNotifierProvider(
          create: (context) => OrderCheckModel(Provider.of(context, listen: false)),
        ),
      ],
      child: Consumer<CartListModel>(
        builder: (context, model, child) {
          switch (model.viewState) {
            case ViewState.busy:
              return Center(
                child: CircularProgressIndicator(),
              );
            case ViewState.error:
              return Center(
                child: Text(model.errorMessage),
              );
            case ViewState.success:
              return Scaffold(
                appBar: AppBar(
                  title: Text('购物车'),
                ),
                body: _BodyWidget(
                  list: model.cartList.carts,
                ),
                bottomNavigationBar: _BottomWidget(
                  cartList: model.cartList,
                ),
              );
            default:
              return Container();
          }
        },
      ),
    );
  }
}

class _BodyWidget extends StatelessWidget {
  final List<Store> list;

  const _BodyWidget({
    Key key,
    @required this.list,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListView.separated(
      padding: EdgeInsets.symmetric(horizontal: 12),
      itemBuilder: (context, index) {
        return _StoreItemWidget(store: list[index]);
      },
      separatorBuilder: (context, index) {
        return Divider(
          height: 12,
          color: Colors.transparent,
        );
      },
      itemCount: list.length,
    );
  }
}

/// 店铺名称
class _StoreItemWidget extends StatelessWidget {
  final Store store;

  const _StoreItemWidget({
    Key key,
    @required this.store,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/cart/img_store.png'),
              fit: BoxFit.fill,
            ),
          ),
          height: 45,
          child: Row(
            children: <Widget>[
              Consumer<OrderCheckModel>(
                builder: (context, model, child) {
                  return CheckBoxWidget(
                    checked: model.getCheckStore(store),
                    onTap: (value) => model.setCheckStore(store, value),
                  );
                },
              ),
              Container(
                padding: EdgeInsets.only(right: 6),
                child: Image.asset('assets/images/cart/ic_store.png', width: 18),
              ),
              Text(
                store.storeName + ' >',
                style: TextStyle(fontSize: 17),
              ),
            ],
          ),
        ),
        Theme(
          data: lightTheme(),
          child: Material(
            borderRadius: BorderRadius.vertical(
              bottom: Radius.circular(10),
            ),
            child: ListView.builder(
              physics: NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              itemBuilder: (context, index) {
                return _ProductItemWidget(
                  cart: store.cartList[index],
                );
              },
              itemCount: store.cartList.length,
            ),
          ),
        ),
      ],
    );
  }
}

/// 商品
class _ProductItemWidget extends StatelessWidget {
  final Cart cart;

  const _ProductItemWidget({
    Key key,
    @required this.cart,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Slidable(
      child: Container(
        height: 110,
        child: Row(
          children: <Widget>[
            Consumer<OrderCheckModel>(
              builder: (context, model, child) {
                return CheckBoxWidget(
                  checked: model.getCheckCart(cart),
                  onTap: (value) => model.setCheckCart(cart, value),
                );
              },
            ),
            ClipRRect(
              borderRadius: BorderRadius.all(Radius.circular(4)),
              child: SizedBox(
                width: 90,
                height: 90,
                child: CachedNetworkImage(
                  imageUrl: cart.productImage,
                  fit: BoxFit.cover,
                ),
              ),
            ),
            Expanded(
              child: Container(
                margin: EdgeInsets.all(12),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      cart.productName,
                      style: TextStyle(fontSize: 16),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    Container(
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        image: DecorationImage(
                          image: AssetImage('assets/images/cart/img_product_params.png'),
                          fit: BoxFit.fill,
                        ),
                      ),
                      width: 76,
                      height: 22,
                      child: Text(
                        '产品属性',
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                    Row(
                      children: <Widget>[
                        Expanded(
                          child: _PriceWidget(
                            list: cart.priceVos,
                          ),
                        ),
                        _CounterWidget(cart: cart)
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
      actionPane: SlidableDrawerActionPane(),
      secondaryActions: <Widget>[
        IconSlideAction(
          color: Colors.red,
          icon: Icons.delete,
          onTap: () => _cartRemove(context, cart.cartId),
        )
      ],
    );
  }

  /// 购物车移除
  void _cartRemove(BuildContext context, int cartId) async {
    CartRemoveModel cartRemoveModel = Provider.of(context, listen: false);
    ViewState viewState = await cartRemoveModel.cartRemove(cartId);
    switch (viewState) {
      case ViewState.error:
        showToast(cartRemoveModel.errorMessage);
        break;
      default:
        CartListModel cartListModel = Provider.of(context, listen: false);
        cartListModel.refreshData();
        break;
    }
  }
}

/// 商品价格
class _PriceWidget extends StatelessWidget {
  final List<Price> list;

  const _PriceWidget({
    Key key,
    @required this.list,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Price rmb;
    Price jfb;
    list.forEach((price) {
      switch (price.coinType) {
        case 'RMB':
          rmb = price;
          break;
        case 'JFB':
          jfb = price;
          break;
      }
    });
    return Text.rich(
      TextSpan(
        text: '￥',
        style: TextStyle(
          color: Theme.of(context).accentColor,
          fontSize: 13,
        ),
        children: [
          if (rmb != null)
            TextSpan(
              text: rmb.pointCoinString,
              style: TextStyle(fontSize: 17),
            ),
          if (jfb != null)
            TextSpan(
              text: '分',
              style: TextStyle(fontSize: 12),
            ),
          if (jfb != null)
            TextSpan(
              text: jfb.pointCoinString,
              style: TextStyle(fontSize: 17),
            ),
        ],
      ),
    );
  }
}

/// 商品数量
class _CounterWidget extends StatelessWidget {
  final Cart cart;

  const _CounterWidget({
    Key key,
    @required this.cart,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return QuantityCounter(
      quantity: cart.quantity,
      onTap: (value) => _cartChange(context, cart.cartId, value),
    );
  }

  /// 修改数量
  void _cartChange(BuildContext context, int cartId, int quantity) async {
    CartChangeModel cartChangeModel = Provider.of(context, listen: false);
    ViewState viewState = await cartChangeModel.cartChange(cartId, quantity);
    switch (viewState) {
      case ViewState.error:
        showToast(cartChangeModel.errorMessage);
        break;
      default:
        CartListModel cartListModel = Provider.of(context, listen: false);
        cartListModel.refreshData();
        break;
    }
  }
}

/// 底部统计
class _BottomWidget extends StatelessWidget {
  final CartList cartList;

  const _BottomWidget({
    Key key,
    @required this.cartList,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Consumer<OrderCheckModel>(
      builder: (context, model, child) {
        double totalRmb = model.totalRmb(cartList);
        double totalJfb = model.totalJfb(cartList);
        int totalQuantity = model.totalQuantity(cartList);
        return Container(
          decoration: BoxDecoration(
            color: Color(0xFF313740),
          ),
          height: 52,
          child: Row(
            children: <Widget>[
              CheckBoxWidget(
                checked: model.getCheckAll(cartList),
                onTap: (value) => model.setCheckAll(cartList, value),
              ),
              Expanded(child: Text('全选')),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.end,
                children: <Widget>[
                  Text.rich(
                    TextSpan(
                      text: '合计：',
                      style: TextStyle(fontSize: 14),
                      children: [
                        TextSpan(
                          text: '￥',
                          style: TextStyle(fontSize: 11),
                        ),
                        TextSpan(
                          text: '$totalRmb',
                          style: TextStyle(fontSize: 18),
                        ),
                        if (totalJfb > 0)
                          TextSpan(
                            text: '分',
                            style: TextStyle(fontSize: 10),
                          ),
                        if (totalJfb > 0)
                          TextSpan(
                            text: '$totalJfb',
                            style: TextStyle(fontSize: 18),
                          ),
                      ],
                    ),
                  ),
                  Text('不含运费', style: TextStyle(fontSize: 11)),
                ],
              ),
              Container(
                width: 96,
                margin: EdgeInsets.symmetric(horizontal: 9),
                child: model.viewState == ViewState.busy
                    ? RaisedButton(
                        onPressed: null,
                        child: SizedBox(
                          width: 14,
                          height: 14,
                          child: CircularProgressIndicator(),
                        ),
                      )
                    : RaisedButton(
                        onPressed: () => _orderCheck(context),
                        child: Text('结算($totalQuantity)'),
                      ),
              ),
            ],
          ),
        );
      },
    );
  }

  void _orderCheck(BuildContext context) async {
    OrderCheckModel model = Provider.of(context, listen: false);
    ViewState viewState = await model.orderCheck(cartList);
    switch (viewState) {
      case ViewState.error:
        showToast(model.errorMessage);
        break;
      default:
        Navigator.of(context).pushNamed('/order/confirm', arguments: model.cartIdQuantity);
        break;
    }
  }
}
